package base

import (
	"strconv"
)

//Department 部门
type Department struct {
	hkey string
}

var deptCache *Department

//GetDepartmentCache 获取部门部门缓存对象
func GetDepartmentCache() (d *Department) {
	if deptCache == nil {
		deptCache = &Department{
			hkey: "department",
		}
	}
	return deptCache
}

//Build 构建
func (d *Department) Build() error {
	Logger.Info("开始构建部门")
	sql := `SELECT DPID,DPNM,PDID,PDNM FROM V_DEPT`
	rows, err := MYDB.Raw(sql).Rows()
	if err != nil {
		return err
	}
	defer rows.Close()
	for rows.Next() {
		var id, pid int
		var name, pname string
		err := rows.Scan(&id, &name, &pid, &pname)
		if err != nil {
			return err
		}
		if err := d.addData(id, name, pid, pname); err != nil {
			return err
		}
	}
	Logger.Info("构建部门完成")
	return nil
}
func (d *Department) addData(id int, name string, pid int, pname string) error {
	key := d.hkey + ":" + strconv.Itoa(id)
	dMap := make(map[string]interface{}, 3)
	dMap["name"] = name
	dMap["pid"] = pid
	dMap["pname"] = pname
	if err := RedisCli.HMSet(rctx, key, dMap).Err(); err != nil {
		return err
	}
	return nil
}

//CacheDept 缓存部门
func CacheDept(id int, name string, pid int, pname string) error {
	return GetDepartmentCache().addData(id, name, pid, pname)
}

//GetNameByID 根据ID获取Name
func (d *Department) GetNameByID(id int) (string, error) {
	key := d.hkey + ":" + strconv.Itoa(id)
	name, err := RedisCli.HGet(rctx, key, "name").Result()
	if err != nil {
		return "", err
	}
	return name, nil
}

//GetPOrgIdByID 根据ID获取pid
func (d *Department) GetPOrgIdByID(id int) (int, error) {
	key := d.hkey + ":" + strconv.Itoa(id)
	pidStr, err := RedisCli.HGet(rctx, key, "pid").Result()
	if err != nil {
		return 0, err
	}
	pid, err := strconv.Atoi(pidStr)
	if err != nil {
		return 0, err
	}
	return pid, nil
}
